var readline = require('readline');

var rl = null;
var questions = [];
var cursor = 0;

function dealQuestions(_self) {
    if(cursor >= questions.length) {
        cursor = 0;questions = [];
        rl.prompt();
        return _self;
    }

    rl.question(questions[cursor].question, function (data) {
        questions[cursor].deal(data);
        ++cursor;
        dealQuestions();
    });
}

var easyREPL = function(){
    if(rl == null) {
        rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });
    }
    return this;
};

var sliceParam = function (line,param) {
    line = line.replace(/\s+/g," ").split(" ");
    for(var i = 0;i<line.length;i++) {
        if(line[i].match(param)) {
            return  line[i+1];
        }
    }
}

/**
 * @description : a liner api to get console input
 * @param : question to ask , function to deal answer
 * */
easyREPL.prototype.question = function(question,dealAnswer){
    easyREPL();
    rl.prompt();
    var _self = this;
    questions.push({question:question,deal:dealAnswer});
    if(questions.length == 1) {
        dealQuestions(_self);
    }
    return this;
};

/**
 * @param : command initialized object
 * */
easyREPL.prototype.command = function(commands){
    easyREPL();
    rl.prompt();
    rl.on("line",function(line) {
        var matchCmd = false;
        for (var tool in commands) {
            if (line.match(new RegExp("^" + tool + "\\s*"))) {
                var matchParam = false;
                var matchNone = false;
                matchCmd = true;
                commands[tool].forEach(function(e){
                   for(var param in e) {
                       param.split(" ").forEach(function(p){
                           if(line.match(new RegExp("\\s+"+p))){
                               matchParam = true;
                               e[param](sliceParam(line,p),line);
                               rl.prompt();
                           }
                       });
                       if(param === 'none') {
                           matchNone = e[param];
                       }
                   }
                });
                if(!matchParam) {
                    if(matchNone && typeof matchNone == 'function') {
                        matchNone();
                        rl.prompt();
                    } else {
                        console.log("wrong param.");
                    }
                }
            }
        }
        if (!matchCmd) {
            console.log("wrong command.");
            rl.prompt();
        }
    });
};

easyREPL.prototype.readline = rl;
easyREPL.prototype.sliceParam = sliceParam;

exports.REPL_Mode = easyREPL;
